package com.jerry.usbserial.util.task.udp

import com.jerry.usbserial.util.hexToByteArray
import java.net.*

/**
 * Created by dugang on 2020/7/7.
 */
class UDPWifiConfigTask(private val ssid: String, private val password: String) : Thread() {
    companion object {
        private const val CLIENT_PORT = 9527
        private const val SERVER_PORT = 5021
        private const val RECEIVE_SIZE = 34
    }

    private val mSocketClient = DatagramSocket(null).apply {
        reuseAddress = true
        bind(InetSocketAddress(CLIENT_PORT))
        soTimeout = 5000
    }
    private var resultListener: ((msg: String?) -> Unit)? = null

    fun setOnResultListener(func: (msg: String?) -> Unit) {
        resultListener = func
    }

    private fun sendData() {
        val cmdList = mutableListOf<Byte>()
        cmdList.addAll("AF4605".hexToByteArray().toList())
        val ssidCmd = ssid.toByteArray()
        cmdList.addAll(ssidCmd.copyInto(ByteArray(33) { 0 }, 0, 0).toList())
        val pwdCmd = password.toByteArray()
        cmdList.addAll(pwdCmd.copyInto(ByteArray(33) { 0 }, 0, 0).toList())
        cmdList.addAll("FA".hexToByteArray().toList())
        val buf = cmdList.toByteArray()
        mSocketClient.send(DatagramPacket(buf, buf.size, InetAddress.getByName("192.168.4.1"), SERVER_PORT))
    }

    override fun run() {
        try {
            sendData()
            val packet = DatagramPacket(ByteArray(RECEIVE_SIZE), RECEIVE_SIZE)
            mSocketClient.receive(packet)
            val receiveInfo = String(packet.data.copyOfRange(0, packet.data.toList().indexOf(0)))
            if (receiveInfo == "ok") {
                resultListener?.invoke("配网成功")
            } else {
                resultListener?.invoke(null)
            }
        } catch (e: SocketTimeoutException) {
            resultListener?.invoke(null)
        } finally {
            mSocketClient.disconnect()
            mSocketClient.close()
        }
    }
}